<?php

declare(strict_types=1);

namespace App\CustHub\Service;

use App\CustHub\Mapper\ChUserGroupMapper;
use App\CustHub\Mapper\ChUserMapper;
use App\CustHub\Model\ChUserExt;
use Hyperf\DbConnection\Db;
use Hyperf\Di\Annotation\Inject;
use Mine\Abstracts\AbstractService;
use Mine\Annotation\Transaction;
use Mine\Exception\NormalStatusException;
use function Hyperf\Collection\data_get;

class ChUserGroupService extends AbstractService
{
    public $mapper;

    #[Inject]
    protected ChUserMapper $userMapper;

    public function __construct(ChUserGroupMapper $mapper)
    {
        $this->mapper = $mapper;
    }

    public function list(array $params): array
    {
        $list = $this->mapper->getGroupList($params,['id','name','parent_id','account_num','seat_quota']);

        $subUserList = $this->userMapper->getSubUserList($params['main_uid'],['id']);

        $totalAccountNum = $subUserList->count();

        $wfzAccountNum = $subUserList->filter(function ($item) {
            return $item->ext->group_id == 0;
        })->count();

        $defaultGroup = [
            [
                'id' => '-1',
                'name' => '全部',
                'account_num' => $totalAccountNum
            ],
            [
                'id' => '0',
                'name' => '未设置分组',
                'account_num' => $wfzAccountNum
            ]
        ];
        
        return array_merge($defaultGroup,arrayToTree($list->toArray()));
    }

    public function getSelectList(array $params)
    {
        $list = $this->mapper->getGroupList($params,['id','name','parent_id','account_num','seat_quota']);
        return arrayToTree($list->toArray());
    }

    /**
     * 删除分组
     * @param array $params
     * @return bool
     * @throws \Exception
     */
    #[Transaction]
    public function deleteGroup(array $params): bool
    {
        $model = $this->mapper->findById($params['id']);
        if(empty($model)){
            throw new NormalStatusException('请选择您要删除的分组');
        }

        $rst = $model->delete();
        if(!$rst){
            throw new NormalStatusException('删除失败，请重试');
        }

        $subIds = $this->mapper->model::query()
            ->where('parent_id',$model->id)
            ->pluck('id')
            ->toArray();
        $ids = [$model->id];
        if(!empty($subIds)){
           $rst = $this->mapper->model::query()
                ->whereIn('id',$subIds)
                ->delete();
            if(!$rst){
                throw new NormalStatusException('删除失败，请重试');
            }

            $ids = array_merge($ids,$subIds);
        }

        ChUserExt::query()
            ->whereIn('group_id',$ids)
            ->update(['group_id' => 0]);
        return true;
    }

    public function getInfo(array $data): array
    {
        $groupId = data_get($data,'group_id',-1);
        if($groupId == -1){
            $seat_quota = -1;
            //获取所有在线的企微号
            $online_robot_cnt = Db::table('ch_user as c')
                ->join('ch_robot as r','c.id','=','r.uid')
                ->where('c.parent_id',$data['main_uid'])
                ->where('r.login_status',1)
                ->count();
        }elseif($groupId == 0){
            $seat_quota = -1;
            $online_robot_cnt = Db::table('ch_user as c')
                ->join('ch_user_ext as e','c.id','=','e.uid')
                ->join('ch_robot as r','c.id','=','r.uid')
                ->where('c.parent_id',$data['main_uid'])
                ->where('e.group_id',0)
                ->where('r.login_status',1)
                ->count();
        }else{

            $seat_quota = $this->mapper->model::query()
                ->where('id',$groupId)
                ->value('seat_quota');

            $online_robot_cnt = Db::table('ch_user as c')
                ->join('ch_user_ext as e','c.id','=','e.uid')
                ->join('ch_robot as r','c.id','=','r.uid')
                ->where('c.parent_id',$data['main_uid'])
                ->where('e.group_id',$groupId)
                ->where('r.login_status',1)
                ->count();
        }

        return [
            'seat_quota' => $seat_quota,
            'online_robot_cnt' => $online_robot_cnt
        ];
    }

    public function setSort(array $params): bool
    {
        $ids = json_decode($params['ids'],true);

        foreach ($ids as $key => $id){
            $this->mapper->model::query()
                ->where('id',$id)
                ->update(['sort' => $key]);
        }
        return true;
    }
}